{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d7cac8ae-d701-4f93-b0d0-93c2d6960861",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# 读取原始CSV文件，指定分隔符为逗号\n",
    "df = pd.read_csv('2022code.csv', header=0, sep=',', quotechar='\"')\n",
    "\n",
    "# 确保将code和name列转换为字符串类型，并去除空格\n",
    "df['code'] = df['code'].astype(str).str.strip()\n",
    "df['name'] = df['name'].astype(str).str.strip()\n",
    "\n",
    "# 创建字典以存储行政区划编码和名称的映射\n",
    "code_name_dict = dict(zip(df['code'], df['name']))\n",
    "\n",
    "# 创建新的DataFrame以存储整理后的数据\n",
    "new_data = []\n",
    "\n",
    "# 遍历每一行数据\n",
    "for index, row in df.iterrows():\n",
    "    code = row['code']  # 行政区划编码\n",
    "    name = row['name']  # 三级行政区域名称\n",
    "    \n",
    "    # 提取行政区域编码的各级信息\n",
    "    level1_code = code[:2] + '0000'  # 一级行政区域编码\n",
    "    level2_code = code[:4] + '00'     # 二级行政区域编码\n",
    "    level3_code = code                 # 三级行政区域编码\n",
    "    \n",
    "    # 根据编码获取对应的名称\n",
    "    level1_name = code_name_dict.get(level1_code, None)\n",
    "    level2_name = code_name_dict.get(level2_code, None)\n",
    "    \n",
    "    # 添加到新数据列表\n",
    "    new_data.append([\n",
    "        index + 1,  # 序号\n",
    "        code,       # 行政区划编码\n",
    "        name,       # 三级行政区域名称\n",
    "        level3_code, # 三级行政区域编码\n",
    "        level2_name, # 所属的二级行政区域名称\n",
    "        level2_code, # 所属的二级行政区域编码\n",
    "        level1_name, # 所属的一级行政区域名称\n",
    "        level1_code  # 所属的一级行政区域编码\n",
    "    ])\n",
    "\n",
    "# 创建新的DataFrame\n",
    "new_df = pd.DataFrame(new_data, columns=[\n",
    "    '序号', '行政区划编码', '三级行政区域名称', '三级行政区域编码',\n",
    "    '所属的二级行政区域名称', '所属的二级行政区域编码',\n",
    "    '所属的一级行政区域名称', '所属的一级行政区域编码'\n",
    "])\n",
    "\n",
    "# 输出到新的CSV文件\n",
    "new_df.to_csv('整理后的2022code.csv', index=False, encoding='utf-8-sig')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4002d07-4af6-40f5-b33a-a7df643adb91",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
